package sample.web;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import org.apache.commons.io.IOUtils;
import sample.controller.MyController;

import java.io.*;
import java.net.URI;
import java.net.URLDecoder;
import java.util.*;

public class WriteAnalysisHistory implements HttpHandler {



    @Override
    public void handle(HttpExchange xchg) throws IOException {

        //允许跨域
        Headers headers = xchg.getResponseHeaders();
        headers.set("Access-Control-Allow-Origin", "*");
        headers.set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        headers.set("Access-Control-Allow-Headers", "Content-Type");


        ///WriteAnalysisHistory66.3.57.17_test2.nmon?[II%22startTime%22:%2214:13:01%22,%22endTime%22:%2214:13:58%22,%22describe%22:%22mmm%22LL]



        String response = "";

        //获得查询字符串(get)
        String header_name =  xchg.getRequestURI().getQuery().split("\\?")[0];
//        String header_name = xchg.getRequestHeaders().getFirst("name");
        try {
            String ip = sample.util.IpRegEx.getIps(header_name).get(0).toString();
            header_name = header_name.substring(ip.length()+1,header_name.length()-5);
        }catch (Exception e){
            System.err.println(e.getMessage());
        }

//        System.err.println(header_name);


        response = response+"\n get:"+"succ";
        //获得表单提交数据(post)
//        String postString = IOUtils.toString(xchg.getRequestBody());
        String postString = xchg.getRequestURI().getQuery().split("\\?")[1].replace("II","{").replace("LL","}").replace("%22","\"");

        //获取下载路径
        System.err.println(MyController.properties.getProperty("downloadPath")+File.separator+header_name+File.separator+header_name+".json");
        //写入到解析文件所在目录
        File file = new File(MyController.properties.getProperty("downloadPath")+File.separator+header_name+File.separator+header_name+".json");
//        File file2 = new File("/Users/wutongchun/IdeaProjects/javaFX/javaFX_ToolsSummary/nmonResult/nnnmmm/result2.json");
        BufferedReader reader = null;
        reader = new BufferedReader(new FileReader(file));
        StringBuilder stringBuilder = new StringBuilder();
        String tempStr;
        //
        while ((tempStr = reader.readLine()) != null) {
            if(tempStr.contains("analysisHistory")){
                stringBuilder.append("  \"analysisHistory\" : \n");
//                String str[] = postString.split(",");
////                for (int i = 0; i < str.length; i++) {
////                    stringBuilder.append(str[i]+"\n");
////                }
                stringBuilder.append(postString+"\n");
                stringBuilder.append("}");
                break;
            }
            stringBuilder.append(tempStr+"\n");
        }
        FileOutputStream fileOutputStream= null;
        fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(stringBuilder.toString().getBytes("utf-8"));
        fileOutputStream.close();
        reader.close();

        //写入dist文件下
        File file2 = new File(new File("").getAbsolutePath()+File.separator+"dist"+File.separator+"js"+File.separator+"app.view.js");
//        File file2 = new File("/Users/wutongchun/IdeaProjects/javaFX/javaFX_ToolsSummary/nmonResult/nnnmmm/result2.json");
        BufferedReader reader2 = null;
        reader2 = new BufferedReader(new FileReader(file2));
        StringBuilder stringBuilder2 = new StringBuilder();

        //dist下的文件更新方式与其他不同，用正则表达式替换
//        System.out.println("analysisHistory\" : "+postString+"}");
        stringBuilder2.append(reader2.readLine().replaceAll("(\\\"analysisHistory\\\" : ).+?(}'\\)})","$1"+postString+"$2"));
        FileOutputStream fileOutputStream2= null;
        fileOutputStream2 = new FileOutputStream(file2);
        fileOutputStream2.write(stringBuilder2.toString().getBytes("utf-8"));
        fileOutputStream2.close();
        reader2.close();

        //写入备份目录下
        File file3 = new File(new File("").getAbsolutePath()+File.separator+"data"+File.separator+header_name+".json");
//        File file2 = new File("/Users/wutongchun/IdeaProjects/javaFX/javaFX_ToolsSummary/nmonResult/nnnmmm/result2.json");
        BufferedReader reader3 = null;
        reader3 = new BufferedReader(new FileReader(file3));
        StringBuilder stringBuilder3 = new StringBuilder();
        //
        while ((tempStr = reader3.readLine()) != null) {
            if(tempStr.contains("analysisHistory")){
                stringBuilder3.append("  \"analysisHistory\" : \n");
//                String str[] = postString.split(",");
////                for (int i = 0; i < str.length; i++) {
////                    stringBuilder.append(str[i]+"\n");
////                }
                stringBuilder3.append(postString+"\n");
                stringBuilder3.append("}");
                break;
            }
            stringBuilder3.append(tempStr+"\n");
        }
        FileOutputStream fileOutputStream3= null;
        fileOutputStream3 = new FileOutputStream(file3);
        fileOutputStream3.write(stringBuilder3.toString().getBytes("utf-8"));
        fileOutputStream3.close();
        reader3.close();




//        Map<String,String> postInfo = formData2Dic(postString);
//        response = response + "\n post:";
//
//        Collection<String> keys = postInfo.keySet();
//        Collection<String> cvalues = postInfo.values();
//        Iterator iterk = keys.iterator();
//
//        response = response + "\n keys:";
//        Iterator itery = cvalues.iterator();
//        while(iterk.hasNext()) {
//            response = response +"  "+iterk.next();
//        }
//        response = response + "\n values:";
//        while(itery.hasNext()) {
//            response = response+"  "+itery.next();
//        }


        xchg.sendResponseHeaders(200,0);
        OutputStream os = xchg.getResponseBody();
        os.write(response.getBytes());
        os.close();



//        Headers headers = xchg.getRequestHeaders();
////        headers.add("Access-Control-Allow-Origin", "*");
//        Set<Map.Entry<String, List<String>>> entries = headers.entrySet();
//
//        StringBuffer response = new StringBuffer();
//        for (Map.Entry<String, List<String>> entry : entries){
//            response.append(entry.toString() + "\n");
//        }
//        // 返回
//        xchg.sendResponseHeaders(200, response.length());
//        OutputStream os = xchg.getResponseBody();
//        os.write(response.toString().getBytes());
//        os.close();
    }


    public static Map<String,String> formData2Dic(String formData ) {
        Map<String,String> result = new HashMap<>();
        if(formData== null || formData.trim().length() == 0) {
            return result;
        }
        final String[] items = formData.split("&");
        Arrays.stream(items).forEach(item ->{
            final String[] keyAndVal = item.split("=");
            if( keyAndVal.length == 2) {
                try{
                    final String key = URLDecoder.decode( keyAndVal[0],"utf8");
                    final String val = URLDecoder.decode( keyAndVal[1],"utf8");
                    result.put(key,val);
                }catch (UnsupportedEncodingException e) {}
            }
        });
        return result;
    }
}